<template>
    <div class="edu-page-warp">
        <ConditionCard
            shadow="never"
            body-style="padding: 24px 24px 6px 24px;"
            @search="onSubmit"
            @reset="reset"
        >
            <el-form :model="queryForm" label-position="right" label-width="120px">
                <el-row :gutter="24" style="height: 50px;">
                    <el-col :span="8">
                        <el-form-item label="年级:">
                            <el-select
                                v-model="queryForm.grade"
                                placeholder="选择年级"
                                style="width: 100%;"
                            >
                                <el-option
                                    v-for="item in options.grade"
                                    :key="item.value"
                                    :label="item.label + '级'"
                                    :value="item.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="培养层次:">
                            <el-select v-model="queryForm.trainingLevel" style="width: 100%;">
                                <el-option
                                    v-for="item in options.trainingLevel"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="培养类别:">
                            <el-select v-model="queryForm.trainingCategory" style="width: 100%;">
                                <el-option
                                    v-for="item in options.trainingCategory"
                                    :key="item.code"
                                    :label="item.name"
                                    :value="item.code"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="学习形式:">
                            <el-select v-model="queryForm.formLearning" style="width: 100%;">
                                <el-option
                                    v-for="item in options.formLearning"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="学院:" style="height:33px;">
                            <el-select
                                v-model="queryForm.departmentId"
                                @change="changeFaculty"
                                style="width: 100%;"
                                :disabled="role != 4" 
                            >
                                <el-option
                                    v-for="item in options.college"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="专业:">
                            <el-select v-model="queryForm.major" style="width: 100%;">
                                <el-option
                                    v-for="item in options.major"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="学位类别:">
                            <el-select
                                v-model="queryForm.studentCategory"
                                placeholder="选择学位类别"
                                style="width: 100%;"
                            >
                                <el-option
                                    v-for="item in options.studentCategory"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="学位类型:">
                            <el-select v-model="queryForm.degreeType" style="width: 100%;"
                                @change="changeFaculty"
                            >
                                <el-option
                                    v-for="item in options.degreeType"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="专项计划:">
                            <el-select
                                v-model="queryForm.spcialPlan"
                                placeholder="选择年级"
                                style="width: 100%;"
                            >
                                <el-option
                                    v-for="item in options.spcialPlan"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8" class="ie-hack">
                        <el-form-item label="在校状态:" prop="leaveSchool">
                            <el-select
                                v-model="queryForm.leaveSchool"
                                filterable
                                style="width: 100%"
                                clearable
                            >
                                <el-option
                                    v-for="item in options.leaveSchool"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="关联状态:">
                            <el-select v-model="queryForm.courseRelStatus" style="width: 100%;">
                                <el-option
                                    v-for="item in options.relate"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="是否国际学生:">
                            <el-select v-model="queryForm.isOverseas" style="width: 100%;">
                                <el-option
                                    v-for="item in options.isOverseas"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="第一外国语码:">
                            <el-select v-model="queryForm.firstForeignLanguage" style="width: 100%;">
                                <el-option
                                    v-for="item in options.firstForeignLanguage"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="导师:" prop="associationStatus">
                            <el-input
                                v-model="queryForm.teacherName"
                                placeholder="输入姓名/工号"
                            />
                        </el-form-item>
                    </el-col> 
                </el-row>
            </el-form>
        </ConditionCard>
        <el-card v-loading="loading" shadow="never" body-style="padding: 24px;" class="card-margin">
            <h1 class="condition-title">学生外国语课程</h1>
            <div class="div-main clearfix">
                <div class="float-left">
                    <el-input
                        v-model="queryForm.name"
                        placeholder="输入学号搜索"
                        style="width:200px"
                        @keyup.enter.native="onSubmit"
                    >
                        <i
                            class="el-icon-search"
                            slot="suffix"
                            style="margin-top:10px;cursor:pointer"
                            @click="onSubmit"
                        ></i>
                    </el-input>
                </div>
                <div class="float-right">
                    <el-button type="primary" @click="pageExport"
                        >页面导出</el-button
                    >
                    <el-button @click="cancelAssociate">取消关联</el-button>
                    <el-button @click="addAssociate">手动关联</el-button>
                    <el-button @click="autoAssociate" type="primary">自动关联</el-button>
                </div>
            </div>
            <el-table stripe :data="students" size="mini" @selection-change="chooseStudent" tooltip-effect="light">
                <el-table-column type="expand">
                    <template slot-scope="props">
                        <el-form
                            label-position="right"
                            inline
                            class="edu-row-expand-4"
                            label-width="110px"
                        >
                            <el-row :gutter="0">
                                <el-col :span="8">
                                    <el-form-item label="学号">
                                        <span>{{ props.row.studentId }}</span>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="姓名">
                                        <span>{{ props.row.name }}</span>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="学院">
                                        <span>{{props.row.departmentId}}</span>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row :gutter="0">
                                <el-col :span="8">
                                    <el-form-item label="专业">
                                        <span>{{props.row.major}}</span>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="培养层次">
                                        <span>{{ props.row.trainingLevel }}</span>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="培养类别">
                                        <span>{{ props.row.trainingCategory }}</span>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row :gutter="0">
                                <el-col :span="8">
                                    <el-form-item label="学位类型">
                                        <span>{{props.row.degreeType}}</span>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="学习形式">
                                        <span>{{props.row.formLearning}}</span>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="年级">
                                        <span>{{ props.row.grade }}</span>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row :gutter="0">
                                <el-col :span="24">
                                    <el-form-item label="第一外国语课程">
                                        <span style="margin-left:20px;" :key="_index" v-for="(course,_index) in props.row.courseCodeList">{{course}}</span>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row :gutter="0">
                                <el-col>
                                    <el-form-item label="备注">
                                        <span>{{props.row.courseRemarks}}</span>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </el-form>
                    </template>
                </el-table-column>
                <el-table-column type="selection" width="50"></el-table-column>
                <el-table-column prop="grade" label="年级"></el-table-column>
                <el-table-column prop="studentId" label="学号"></el-table-column>
                <el-table-column prop="name" label="姓名"></el-table-column>
                <el-table-column prop="trainingLevel" label="培养层次"></el-table-column>
                <el-table-column prop="departmentId" label="学院" min-width="150px" show-overflow-tooltip></el-table-column>
                <el-table-column prop="major" label="专业" min-width="150px" show-overflow-tooltip></el-table-column>
                <el-table-column prop="formLearning" label="学习形式" width="80"></el-table-column>
                <el-table-column label="第一外国语课程" min-width="300px" show-overflow-tooltip>
                    <template slot-scope="props">
                        <div style="padding: 3px 0" :key="_index" v-for="(course,_index) in props.row.courseCodeList">{{course}}</div>
                    </template>
                </el-table-column>
                <!-- <el-table-column label="国际学生" prop="isOverseas" width="80"/> -->
                <el-table-column label="导师" prop="teacherName" width="80"/>
                <el-table-column label="状态">
                    <template slot-scope="props">
                        <span>{{props.row.courseCode?'已关联': '未关联'}}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="80">
                    <template slot-scope="scope">
                        <el-button
                            v-if="scope.row.courseCode==null"
                            type="text"
                            @click="relateCourse(scope.row)"
                            size="mini"
                        >关联</el-button>
                        <el-button
                            v-if="scope.row.courseCode"
                            type="text"
                            @click="cancelRelateCourse(scope.row)"
                            size="mini"
                        >取消关联</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-row>
                <el-col>
                    <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="queryForm.pageNum_"
                        :page-sizes="[20, 50,100,500,1000]"
                        :page-size="queryForm.pageSize_"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="queryForm.total_"
                        style="float:right;margin-top:10px"
                    ></el-pagination>
                </el-col>
            </el-row>
        </el-card>
        <el-dialog title="课程映射关系" width="50%" :visible.sync="showRelateDialog" :close-on-click-modal="false"
            :close-on-press-escape="false">
            <div>
                <el-row :gutter="20">
                    <el-col :span="24" :style="isCourseBox?height:''">
                        <div style="positon:relative">
                             <el-input
                                v-model="foreignCollegeName"
                                placeholder="请输入课程名或者外国语码"
                                style="width:200px"
                                @keyup.enter.native="changeCourse"
                            >
                                <i
                                    class="el-icon-search"
                                    slot="suffix"
                                    style="margin-top:10px;cursor:pointer"
                                    @click="changeCourse"
                                ></i>
                            </el-input>
                            <div class="course-box clearfix" v-show="isCourseBox">
                                <el-col :span="24">
                                   <template v-if="courseBox.length > 0">
                                        <div>
                                        <el-checkbox-group v-model="checkList">
                                            <el-checkbox v-for="course in courseBox" :label="course.id" :key="course" style="dispaly:block">{{course.courseCode}}{{course.courseName}}(国标码：{{course.languageCode}})</el-checkbox>
                                        </el-checkbox-group>
                                    </div>
                                    <div style="margin:20px 0;    text-align: right;">
                                        <el-button @click="submitcourseBox" type="primary">确定</el-button>
                                        <el-button @click="cancelCourseBoxChecked">取消</el-button>
                                    </div>
                                    </template>
                                    <template v-else>
                                        <p>暂无数据，请重新查询</p>
                                    </template>
                                </el-col>
                            </div>
                        </div>
                        <!-- <el-form-item label="第一外国语课程(校标)">
                            <el-select
                                v-model="relateForm.foreignCollegeName"
                                remote
                                placeholder="请输入课程名或者外国语码"
                                filterable
                                :remote-method="selectCourses"
                                size="mini"
                                style="width:100%"
                                @change="changeSelectCourse"
                            >
                                <el-option
                                    v-for="item in collegeCodes"
                                    :key="item.value"
                                    :label="item.value"
                                    :value="item.value"
                                >({{item.value}})&nbsp;{{item.label}}</el-option>
                            </el-select>
                            
                        </el-form-item> -->
                    </el-col>
                    <!-- <el-col :span="12">
                        <el-form-item label="第一外国名称(校标)">
                            <el-input v-model="relateForm.foreignCollegeName" disabled="true"/>
                        </el-form-item>
                    </el-col>-->
                </el-row>
                <el-row :gutter="20" v-show="!isCourseBox">
                    <el-col :span="24">
                         <el-table stripe :data="checkCourses" style="width: 100%;margin:30px 0"  tooltip-effect="light">
                            <el-table-column prop="languageCode" label="第一外国语码（国标）" min-width="180px"></el-table-column>
                            <el-table-column prop="courseCode" label="课程代码"></el-table-column>
                            <el-table-column prop="courseName" label="课程名称" min-width="200px" show-overflow-tooltip></el-table-column>
                            <el-table-column  prop="courseNameEn" label="课程名称（英文）" min-width="200px" show-overflow-tooltip></el-table-column>
                            <el-table-column label="操作">
                                <template slot-scope="props">
                                    <el-button
                                        type="text"
                                        @click="deleteCourse(props.row)"
                                        size="mini"
                                    >删除</el-button>
                                </template>
                            </el-table-column>
                         </el-table>
                    </el-col>
                </el-row>
                <el-row v-show="!isCourseBox">
                    <el-col :span="24">
                        <div class="float-right no-bottom no-right">
                            <el-button @click="confirmRelate" type="primary">确定</el-button>
                            <el-button @click="cancelRelateDialog">取消</el-button>
                        </div>
                    </el-col>
                </el-row>
            </div>
        </el-dialog>
        <el-dialog title="自动关联结果提示" width="45%" :visible.sync="showResult" :close-on-click-modal="false"
            :close-on-press-escape="false">
            <div style="font-size:18px">
                <i class="el-icon-warning"></i>
                <span>
                    本次共需关联{{result.must}}个,
                    <b style="color:green">成功{{result.success}}</b>个,
                    <b style="color:red">失败{{result.fail}}</b>个.
                </span>
            </div>
            <div style="margin:10px 0">
                <div>
                    无法匹配第一外国语码：
                    <b style="color:red">{{result.fisrtLanguageIsNull}}</b>个，无法匹配第一外国语课程：
                    <b style="color:red">{{result.courseIdIsNull}}</b>个
                </div>
            </div>
            <div v-if="result.fail&&result.path">
                <el-button type="text" @click="download" size="mini">点击下载excel查看详情</el-button>
            </div>
            <div style="text-align:right">
                <el-button @click="closeResultDialog" type="primary">确定</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import bus from 'common/src/utils/bus';
import { queryDic , findTrainingLevelByProjId, sortTrainingCategories} from "common/src/api/dictionary";
import { getGraduateDegreePage } from "common/src/api/resource/course";
import { findFaculty } from "common/src/api/faculty";
import { getCourseList } from "common/src/api/courseTemplate";
import { getPower , queryAddCourseList, queryCourseListByCodes ,exportPage} from 'common/src/api/culture/culturePlan';
import {
    findStudentCultureRelList,
    batchUpdateFirstLanguageCourses,
    autoUpdateFirstLanguageCourses,
    firstLanguageContrast,
    getAutoUpdateResult
} from "common/src/api/culture/culturePlan";
import UTILS from "common/src/utils/utils";
import mixin from 'common/src/mixins/index';
const RELATE_TYPE = {
    SINGLE: "SINGLE",
    BATCH: "BATCH"
};
export default {
    name: "foreignCourse",
    mixins: [mixin],
    data() {
        return {
            showRelateDialog: false,
            collegeCodes: [],
            relateId: "", //关联id
            relateType: "", //关联类型
            relateForm: {
                foreignInternationalCode: "",
                foreignInternationalName: "",
                foreignCollegeCode: "",
                foreignCollegeName: "",
                remark: ""
            },
            studentId:"",
            queryForm: {
                grade: "",
                trainingLevel: "",
                degreeType: "",
                departmentId: "",
                major: "",
                formLearning: "",
                spcialPlan: "",
                courseRelStatus: "",
                studentCategory: "",
                trainingCategory: "",
                name: "", //学号
                pageSize_: 20,
                pageNum_: 1,
                total_: 0,
                projId: "",
                isOverseas:"",
                teacherName:"",
                leaveSchool:"1",
                firstForeignLanguage:""
            },
            options: {
                grade: [],
                trainingLevel: [], //培养层次
                formLearning: [], //学习形式
                degreeType: [], //学位类型
                college: [], //学院
                spcialPlan: [], //专项计划
                major: [], //专业
                studentCategory: [], //学位类别
                trainingCategory: [], //培养类别
                projIds: [],
                relate: [
                    {
                        label: "已关联",
                        value: 1
                    },
                    {
                        label: "未关联",
                        value: 2
                    }
                ],
                isOverseas: [
                    {
                        label: "否",
                        value: 0
                    },
                    {
                        label: "是",
                        value: 1
                    }
                ],
                firstForeignLanguage:[]
            },
            height:"min-height:377px",
            students: [],
            chooseStudents: [],
            showResult: false,
            role:'',
            leaveSchool:[],
            checkCourses:[],
            courseBox:[],
            isCourseBox: false,
            checkList:[],
            foreignCollegeName:'',
            result: {
                must: "",
                success: "",
                fail: "",
                courseIdIsNull: "",
                fisrtLanguageIsNull: "",
                path: ""
            }
        };
    },
    mounted: function() {
        this.init();
        this.getRole();
        this.initProjId();
        this.initTrainingLevelOptions();
        bus.$on('updateCurrentManageDeptId', (id) => {
            this.queryForm.projId = id;
            this.initTrainingLevelOptions();
            this.onSubmit();
        })
    },
    methods: {
        initProjId(){
            let currentUser = (this.$store.state.session && this.$store.state.session.user) || JSON.parse(localStorage.getItem('user')); 
            this.queryForm.projId = currentUser.currentManageDptId;
        },
        initTrainingLevelOptions(){
            findTrainingLevelByProjId(this.queryForm.projId).then(res => {
                if (res.code === 200) {
                    this.queryForm.trainingLevel = "";
                    this.loadTrainingLevelOptions("trainingLevel", res.data);
                }
            });
            firstLanguageContrast(this.queryForm.projId).then(res => {
                if (res.code === 200) {
                    this.queryForm.firstForeignLanguage = "";
                    this.options["firstForeignLanguage"] = [];
                    _.each(res.data.list, level => {
                        this.options["firstForeignLanguage"].push({
                            label:level.languageCode,
                            value: level.languageCode
                        });
                    });
                    this.options.firstForeignLanguage= _.uniqBy(this.options.firstForeignLanguage, 'value');
                }
            });
        },
        loadTrainingLevelOptions(optionKey, dataObj) {
            this.options[optionKey] = [];
            _.each(dataObj, level => {
                this.options[optionKey].push({
                    label:
                        "en" === this.$store.getters.language
                            ? level.nameEN
                            : level.nameCN,
                    value: level.code
                });
            });
        },
        getRole(){
            getPower().then((res) => {
                this.role = res.data.power
                if(res.data.departmentCode.indexOf(",") !=-1){
                    let departmentCode = res.data.departmentCode.split(",")
                    this.queryForm.departmentId = departmentCode[0]
                }else{
                    this.queryForm.departmentId = res.data.departmentCode
                }
                if(res.data.departmentCode && res.data.power == 3){
                    this.queryCampusMajor()
                }
            })
        },
        init() {
            //绑定年级
            let now = new Date();
            let currentYear = now.getFullYear() + 1,
                minYear = currentYear - 6;
            for (let grade = currentYear; grade > minYear; grade--) {
                let obj = { label: grade, value: grade };
                this.options.grade.push(obj);
            }
            findFaculty().then(res => { 
                let data = {"X_YX": res.data};
                UTILS.fillSelect({ college: "X_YX" }, data, this.options);
            });
            let data = {
                lang: this.$store.getters.language || "cn",
                type: "allChild",
                keys: [
                    //"X_PYCC",
                    "K_XXXS",
                    "X_ZXJH",
                    "X_PYLB",
                    "X_XWLB",
                    "X_XWLX",
                    "X_LXZT",
                    "X_GLBM"
                ]
            };
            queryDic(data).then(res => {
                if (res.code == 200) {
                    let params = {
                        lang: this.$store.getters.language,
                        keys: ["X_PYLB"]
                    };
                    sortTrainingCategories(params).then((res) => {
                        this.options.trainingCategory = res.data.X_PYLB;
                    });
                    UTILS.fillSelect(
                        {
                            //trainingLevel: "X_PYCC",
                            studentCategory: "X_XWLB",
                            spcialPlan: "X_ZXJH",
                            formLearning: "K_XXXS",
                            degreeType: "X_XWLX",
                            // trainingCategory: "X_PYLB",
                            projIds: "X_GLBM",
                            leaveSchool: "X_LXZT"
                        },
                        res.data,
                        this.options
                    );
                    if (this.options.projIds.length > 0) {
                        this.queryForm.projId = this.options.projIds[0].value;
                        this.onSubmit();
                    }
                }
            });
        },
        reset() {
             if(this.role == 3){
                this.queryForm.grade = "";
                this.queryForm.trainingLevel = "";
                this.queryForm.major = "";
                this.queryForm.degreeType = "";
                this.queryForm.formLearning = "";
                this.queryForm.spcialPlan = "";
                this.queryForm.courseRelStatus = "";
                this.queryForm.trainingCategory = "";
                this.queryForm.studentCategory = "";
                this.queryForm.name = "";
                this.queryForm.teacherName = "";
                this.queryForm.isOverseas = "";
                this.queryForm.firstForeignLanguage = "";
                this.getStudentList();
            }else{
                this.queryForm.grade = "";
                this.queryForm.trainingLevel = "";
                this.queryForm.departmentId = "";
                this.queryForm.major = "";
                this.queryForm.degreeType = "";
                this.queryForm.formLearning = "";
                this.queryForm.spcialPlan = "";
                this.queryForm.courseRelStatus = "";
                this.queryForm.trainingCategory = "";
                this.queryForm.studentCategory = "";
                this.queryForm.name = "";
                this.queryForm.teacherName = "";
                this.queryForm.isOverseas = "";
                this.queryForm.firstForeignLanguage = "";
                this.getStudentList();
            }
        },
        onSubmit() {
            this.getStudentList();
        },
        //选择复选框
        chooseStudent(val) {
            this.chooseStudents = val;
        },
        //获取学生列表
        getStudentList(isFirstPage = true) {
            if (isFirstPage) {
                this.queryForm.pageNum_ = 1;
            }
            findStudentCultureRelList(this.queryForm)
                .then(response => {
                    if (response.code == 200) {
                        this.students = response.data.list;
                        this.queryForm.total_ = response.data.total_;
                    } else {
                        throw "error";
                    }
                })
                .catch(e => {
                    this.$message({
                        type: "error",
                        message: "查询学生外国课程失败"
                    });
                });
        },
        //查询专业
        changeFaculty() {
            this.queryForm.major = "";
            this.options["major"] = [];
            let promise = this.getGraduateDegreePage();
            promise.then(response => {
                if (response.code === 200) {
                    response.data.list.map(item =>{
                        this.options["major"].push({
                            value: item.code,
                            label: item.name
                        })
                    });
                }
            });
        },
        getGraduateDegreePage() {
            const data = {
                college: this.queryForm.departmentId,
                type:this.queryForm.degreeType,
                page: false
            };
            return getGraduateDegreePage(data);
        },
        handleSizeChange(val) {
            this.queryForm.pageSize_ = val;
            this.getStudentList();
        },
        handleCurrentChange(val) {
            this.queryForm.pageNum_ = val;
            this.getStudentList(false);
        },
        //单个取消关联
        cancelRelateCourse(row) {
            this.$confirm("此操作将解除绑定关系, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(()=>{
                batchUpdateFirstLanguageCourses({
                    idList: [{ id: row.id }],
                    courseCode: null
                }).then(response => {
                    if (response.code == 200) {
                        this.$message({
                            type: "success",
                            message: "取消关联成功"
                        });
                        this.onSubmit();
                    }
                });
            })   
        },
        //取消关联
        cancelAssociate() {
            if (this.chooseStudents.length == 0) {
                this.$message({
                    type: "info",
                    message: "请选择要取消关联的学生"
                });
                return;
            }
            if(this.chooseStudents.length>0) {
                this.$confirm("此操作将解除绑定关系, 是否继续?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(()=>{
                    let idList = this.chooseStudents.map(c => {
                        return { id: c.id };
                    });
                    batchUpdateFirstLanguageCourses({ idList, courseCode: null }).then(
                        response => {
                            if (response.code == 200) {
                                this.$message({
                                    type: "success",
                                    message: "取消关联成功"
                                });
                                this.onSubmit();
                            }
                        }
                    );
                })
            }
        },
        //打开批量关联课程对话框
        addAssociate() {
            if (this.chooseStudents.length == 0) {
                this.$message({
                    type: "info",
                    message: "请选择要添加关联的学生"
                });
                return;
            }
            this.resetRelate();
            this.relateType = RELATE_TYPE.BATCH;
            this.showRelateDialog = true;
        },
        //打开单个关联课程对话框
        relateCourse(row) {
            this.resetRelate();
            this.relateType = RELATE_TYPE.SINGLE;
            this.relateId = row.id;
            //this.studentId = row.studentId;
            this.relateForm.foreignCollegeCode = row.courseCode;
            //this.selectCourses(this.relateForm.foreignCollegeCode);
            this.showRelateDialog = true;
        },
        //确定关联
        confirmRelate() {
            if (this.checkCourses.length == 0) {
                this.$message({
                    type: "warning",
                    message: "请选择需要关联的课程"
                });
                return;
            }
            let ids =
                this.relateType == RELATE_TYPE.SINGLE
                    ? [{ id: this.relateId }]
                    : this.chooseStudents.map(c => {
                          return { id: c.id };
                      });
            // let obj = this.collegeCodes.find(
            //     c => c.value == this.relateForm.foreignCollegeCode
            // );
            // if (!obj) return;
            let obj =[];
            this.checkCourses.forEach(d =>{
                obj.push(d.courseCode)
            })
            batchUpdateFirstLanguageCourses({
                idList: ids,
                courseCode: obj.toString(),
                courseRemarks: this.relateForm.remark
            })
                .then(response => {
                    if (response.code == 200) {
                        this.$message({
                            type: "success",
                            message: "关联成功"
                        });
                        this.showRelateDialog = false;
                        this.checkCourses = [];
                        this.onSubmit();
                    } else {
                        throw "error";
                    }
                })
                .catch(e => {
                    this.$message({
                        type: "error",
                        message: "关联失败"
                    });
                });
        },
        //重置关联表单
        resetRelate() {
            this.relateForm.foreignInternationalCode = "";
            this.relateForm.foreignInternationalName = "";
            this.relateForm.foreignCollegeCode = "";
            this.relateForm.foreignCollegeName = "";
            this.relateForm.remark = "";
            this.collegeCodes.length = 0;
        },
        //取消关联对话框
        cancelRelateDialog() {
            this.resetRelate();
            this.showRelateDialog = false;
            this.isCourseBox = false;
            this.checkList = [];
            this.checkCourses = []
            this.foreignCollegeName = ""
            this.courseBox = [];
        },
        //搜索远程课程列表
        selectCourses(query) {
            this.collegeCodes.length = 0;
            getCourseList({
                trainingLevel: "",
                formLearning: "",
                studentAbroad: "",
                condition: query,
                isElective: "",
                pageSize_: 20,
                pageNum_: 1,
                total_: 0
            })
                .then(response => {
                    if (response.code == 200) {
                        const list = response.data.list || [];
                        for (var i = 0; i < list.length; i++) {
                            this.collegeCodes.push({
                                label: list[i] && list[i].name,
                                value: list[i] && list[i].code,
                                id: list[i] && list[i].id
                            });
                        }
                    } else {
                        throw "";
                    }
                })
                .catch(e => {});
        },
        //远程搜索的课程
        changeCourse() {
            this.isCourseBox = true;
            queryAddCourseList(this.foreignCollegeName).then(response => {
                    if (response.code == 200) {
                        this.courseBox = response.data.list
                    } else {
                        throw "";
                    }
                })
            // let option = this.collegeCodes.find(option => option.value == val);
            // if (option) {
            //     this.relateForm.foreignCollegeName = option.label;
            //     this.relateForm.foreignCollegeCode = option.value;
            // } else {
            //     return "";
            // }
        },
        // submitcourseBox(){
        //     this.foreignCollegeName = "";
        //     this.isCourseBox = false;
        //     queryCourseListByCodes(this.checkList).then(response => {
        //             if (response.code == 200) {
        //                 if(response.data && response.data.length > 0){
        //                     response.data.forEach((d,index) =>{
        //                         if(this.checkCourses.length > 0){
        //                             if(d.languageCode != this.checkCourses[index].languageCode){
        //                                 this.checkCourses.push(d)
        //                             }
        //                         }else{
        //                             this.checkCourses.push(d)
        //                         }
        //                         this.checkList = [];    
        //                     })  
        //                 }
        //             } else {
        //                 throw "";
        //             }
        //         })
        // },
        submitcourseBox(){
            this.foreignCollegeName = "";
            this.isCourseBox = false;
            let _this = this
            queryCourseListByCodes(this.checkList).then(response => {
                    if (response.code == 200) {
                        if(response.data && response.data.length > 0){
                            response.data.forEach((d,index) =>{
                                if(_this.checkCourses.length > 0){
                                    let has = _this.checkCourses.some((item)=>{
                                        return item.courseCode == d.courseCode && item.languageCode == d.languageCode
                                    })
                                    if(!has){
                                        _this.checkCourses.push(d)
                                    }
                                }else{
                                    _this.checkCourses.push(d)
                                }
                                _this.checkList = [];
                            })
                        }
                    } else {
                        throw "";
                    }
                })
        },
        cancelCourseBoxChecked(){
            this.isCourseBox = false;
            this.checkList = [];
            this.foreignCollegeName = ""
            this.courseBox = [];
        },
        deleteCourse(row){
            this.checkCourses = this.checkCourses.filter(d => d.id != row.id)
        },
        //自动关联
        autoAssociate() {
            let condition = this.queryForm;
            let title = "是否按筛选条件自动关联?";
            if (this.chooseStudents.length > 0) {
                condition = {
                    grade: "",
                    departmentId: "",
                    projId:this.global.projectId,
                    major: "",
                    studentIds: this.chooseStudents.map(c => c.studentId)
                };
                title = "是否按选中学生自动关联?";
            } else {
                
              //  if (this.queryForm.grade == "") {
                    this.$message({
                        type: "info",
                        message: "请选择要关联的学生"
                    });
                    return;
              //  }
            }
            this.$confirm(title, "提示", {
                confirmButtonText: this.$t("message.confirm"),
                cancelButtonText: this.$t("message.cancel"),
                type: "warning"
            }).then(() => {
                const loading = this.$loading({
                    lock: true,
                    text: "Loading",
                    spinner: "el-icon-loading",
                    background: "rgba(255, 255, 255, .48)"
                });
                let sleep = ms => {
                    return new Promise(resolve => setTimeout(resolve, ms));
                };
                let loaded = false;
                let key = "";
                //重复发送请求，直到自动关联完成
                let delayRequest = async () => {
                    if (loaded) {
                        await sleep(5000);
                    } else {
                        loaded = true;
                    }
                    getAutoUpdateResult(key)
                        .then(res => {
                            if (res.code == 200 && res.data.status) {
                                this.showResult = true;
                                this.result.must = res.data.must;
                                this.result.success = res.data.success;
                                this.result.fail = res.data.fail;
                                this.result.courseIdIsNull =
                                    res.data.courseIdIsNull;
                                this.result.fisrtLanguageIsNull =
                                    res.data.fisrtLanguageIsNull;
                                this.result.path = res.data.path;
                                loading.close();
                                this.onSubmit();
                            } else {
                                delayRequest();
                            }
                        })
                        .catch(ex => {
                            delayRequest();
                        });
                };

                autoUpdateFirstLanguageCourses(condition).then(res => {
                    if (res.code == 200) {
                        key = res.data.key;
                        delayRequest();
                    }
                });
            });
        },
        download() {
            window.open(
                "/api/cultureservice/studentCultureRel/export?path=" +
                    this.result.path
            );
        },
        closeResultDialog() {
            this.showResult = false;
        },
        pageExport() {
            let ids = this.chooseStudents.map(item => item.studentId);
            let params = _.cloneDeep(this.queryForm);
            exportPage(
                Object.assign(params, {
                    ids: ids + ""
                }),'exportStudentCultureRelFirstList',"学生外国语课程"
            );
        }
    },
    watch: {
        showRelateDialog: function(_n, _o){
            console.log(_n)
            if(_n == false){
                this.isCourseBox = false;
                this.checkList = [];
                this.checkCourses = []
                this.foreignCollegeName = ""
                this.courseBox = []; 
            }
        }
    }
};
</script>
<style scoped>
    .div-main {
        margin-bottom: 16px;
    }
    .course-box{
        position: absolute;
        left: 10px;
        top:33px;
        right: 0;
        padding-top: 20px;
        background: #fff;
        border: 1px solid #eee;
        z-index: 99999;
    }
    .el-checkbox{
        display: block !important;
        margin-left: 30px;
        margin-bottom: 10px;
    }
</style>